package com.example.statistics.ex

import com.example.statistics.R
import com.example.statistics.utils.FileUtils
import com.jhj.httplibrary.HttpCall
import com.jhj.httplibrary.callback.BaseHttpCallback
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.*
import java.net.HttpURLConnection
import java.net.URL
import java.text.DecimalFormat
import java.util.*

/**
 * 文件名
 */
val String.fileName: String
    get() {
        val index = this.lastIndexOf("/")
        if (index != -1) {
            return substring(index + 1, this.length)
        }
        return this
    }

/**
 * 文件后缀（eg、".png",".doc"）
 */
val String.fileSuffix: String
    get() {
        val index = this.lastIndexOf(".")
        if (index != -1) {
            return substring(index, this.length)
        }
        return ""
    }

val File.fileSize: String
    get() {
        val length = this.length()
        return length.fileSize
    }

val Long.fileSize: String
    get() {
        val df = DecimalFormat("#.00")
        var fileSizeString = ""
        val wrongSize = "0B"
        if (this == 0L) {
            return wrongSize
        }
        if (this < 1024) {
            fileSizeString = df.format(this.toDouble()) + "B"
        } else if (this < 1024 * 1024) {
            fileSizeString = df.format(this.toDouble() / 1024) + "KB"
        } else if (this < 1024 * 1024 * 1024) {
            fileSizeString = df.format(this.toDouble() / (1024 * 1024)) + "MB"
        } else {
            fileSizeString = df.format(this.toDouble() / 1073741824) + "GB"
        }
        return fileSizeString
    }

@Throws(Exception::class)
suspend fun String.fileSize(): Long {
    return withContext(Dispatchers.IO) {
        if (startsWith("http")) {
            val url = URL(this@fileSize)
            val urlConnection = url.openConnection() as HttpURLConnection
            urlConnection.connectTimeout = 5 * 1000
            urlConnection.requestMethod = "GET"
            urlConnection.connect()
            urlConnection.contentLength.toLong()
        } else {
            val file = File(this@fileSize)
            file.length()
        }
    }
}


/**
 * 格式化文件路径
 */
val String?.filePath: String
    get() {
        if (this != null) {
            return if (isUrl()) {
                this.replace("\\", "/")
            } else {
                HttpCall.baseUrl + this.replace("\\", "/")
            }
        }
        return ""
    }

/**
 * 文件类型对应的图标
 */
val String.fileTypeIcon: Any
    get() = when (this.fileSuffix.toLowerCase(Locale.getDefault())) {
        ".doc", ".docx" -> R.mipmap.ic_file_word
        ".xls", ".xlsx" -> R.mipmap.ic_file_excel
        ".ppt", ".pptx" -> R.mipmap.ic_file_ppt
        ".pdf", ".PDF" -> R.mipmap.ic_file_pdf
        ".ogg", ".mp3", ".wav" -> R.mipmap.ic_file_audio
        ".txt", ".TXT" -> R.mipmap.ic_file_txt
        ".jpg", ".png" -> HttpCall.baseUrl + this
        else -> R.mipmap.ic_file_unknow
    }

fun createFileWithByte(byteArray: ByteArray, filePath: String) {
    val file = File(filePath)
    var outputStream: FileOutputStream? = null
    var bufferedOutputStream: BufferedOutputStream? = null
    try {
        if (file.exists()) {
            file.delete()
        }
        file.createNewFile()
        outputStream = FileOutputStream(file)
        bufferedOutputStream = BufferedOutputStream(outputStream)
        val buff = ByteArray(1024)
        val bis = ByteArrayInputStream(byteArray)
        var len = bis.read(buff)
        while (len != -1) {
            bufferedOutputStream.write(buff, 0, len)
            len = bis.read(buff)

        }
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
    } finally {
        bufferedOutputStream?.flush()
        bufferedOutputStream?.close()
        outputStream?.close()
    }
}



